//
// Created by Administrator on 2022/10/12.
//
//使用链式存储结构实现线性表
#include <malloc.h>
#include <stdio.h>

#define OK 1
#define ERROR 0
typedef int ElemType;

typedef struct Node {
    ElemType Data;
    struct Node* next;
}Node;
typedef struct Node* LinkedList;

//获取第i个元素
int getElem(LinkedList list,int i,ElemType* e){
    LinkedList p = list->next; /* 定义指针p指向头节点 */
    if(i<1){
        return ERROR;
    }
    int j = 1;
    while(p && j<i){
        p=p->next;
        j++;
    }
    if(!p ){ /* p为空 */
        return ERROR;
    }
    *e= p->Data;
    return OK;
}
//向单链表中插入一个元素
int insertElem(LinkedList *list ,int i,ElemType e){

    LinkedList p = *list; /* 定义指针p指向头节点 */
    if(i<1){
        return ERROR;
    }
    int j = 1;
    while(p && j<i-1){
        p=p->next;
        j++;
    }
    if(!p ){ /* p为空 */
        return ERROR;
    }
    LinkedList insert = (LinkedList)malloc(sizeof(Node));
    insert->Data= e;
    insert->next=p->next;
    p->next = insert;
    return OK;
}
//删除单链表中的一个元素
int delElm(LinkedList *list,int i,ElemType *e){
    LinkedList p = *list; /* 定义指针p指向头节点 */
    if(i<1){
        return ERROR;
    }
    int j = 1;
    while(p && j<i-1){
        p=p->next;
        j++;
    }
    if(!p ){ /* p为空 */
        return ERROR;
    }
    *e = p->next->Data;
    p->next = p->next->next;
    free(p->next);
    return OK;
}
//新建一个链表,并随机插入i个数据,头插法
void createLinkedList(LinkedList* list,int i){
    LinkedList p ;
    *list = (LinkedList) malloc(sizeof(Node)); /* 创建一个头节点 */
    (*list)->next = NULL;
    //头插法,通过头节点将节点插入
    for (int j = 0; j < i; ++j) {
        p = (LinkedList) malloc(sizeof(Node));
        p->Data = j;
        p->next = (*list)->next;
        (*list)->next=p;
    }

}
//新建一个链表,并随机从插入i个数据,采用尾插法

void createLinkedList2 (LinkedList * list,int i ){
        *list = (LinkedList)malloc(sizeof(Node));
        LinkedList p = *list;
        LinkedList q;
        p->next = NULL;
    for (int j = 0; j < i; ++j) {
        q = (LinkedList) malloc(sizeof(Node));
        q->Data = j;
        q->next = 0;
        p->next = q;
        p=p->next;
    }
    p->next =NULL;
}
//显示单链表中的每个元素
void showLinkedList (LinkedList list){
    LinkedList p = list->next;
    while(p){
        printf("%d\n",p->Data);
        p=p->next;
    }
}
//删除整个单链表
void deleteLinkedList(LinkedList* list){
    LinkedList p,q;
    p=(*list)->next;
    while(p){
        q = p->next; /* 保存下一个节点 */
        free(p);
        p=q;
    }
    (*list)->next = NULL;/* 头指针下一个节点指向空,不然可能出现内存泄露 */
}

void main(){
    LinkedList l;

    createLinkedList2(&l,9);

    showLinkedList(l);
    deleteLinkedList(&l);
    showLinkedList(l);

}